package com.mqtt.ctwingmqtt.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;

import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandRequest;
import com.mqtt.ctwingmqtt.domain.CtwEntity;
import com.mqtt.ctwingmqtt.domain.PageResult;
import com.mqtt.ctwingmqtt.domain.entity.Command;
import com.mqtt.ctwingmqtt.mapper.CtwingMapper;
import com.mqtt.ctwingmqtt.mapper.IIMapper;
import com.mqtt.ctwingmqtt.service.CtwingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CtwingServiceImpl implements CtwingService {
    @Autowired
    private CtwingMapper ctwingMapper;
    @Autowired
    private IIMapper iimapper;
    @Override
    public void addMessage(String deviceAddress, String string, String s, String username,Boolean flag,String commandId,Integer productId,String deviceId,String masterKey) {
        Command command = new Command();
        //传入设备id，指令，回复数据，用户名
        command.setDeviceAddress(deviceAddress);
        command.setCommandText(string);
        command.setResponseBody(s);
        command.setUserName(username);
        command.setCommandId(commandId);
        command.setProductId(productId);
        command.setDeviceId(deviceId);
        command.setMasterKey(masterKey);
        //设置时间为当前时间
        command.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
        command.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
        if(flag){
            command.setSendStatus("已发送成功");
        }
        else {
            command.setSendStatus("未发送成功");
        }
        ctwingMapper.insert(command);
    }

    @Override
    public PageResult<Command> commandPage(Long pageNum, Long pageSize, String deviceAddress) {
            Page<Command> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Command> queryWrapper = Wrappers.query();
            if(deviceAddress !=null){
               queryWrapper.eq("device_address", deviceAddress);
            }
            Page<Command> devicePage = ctwingMapper.selectPage(page, queryWrapper);
            List<Command> records = devicePage.getRecords().stream()
                .collect(Collectors.toList());
            // 5. 封装分页结果
            PageResult<Command> pageResult = new PageResult<>();
            pageResult.setTotal(devicePage.getTotal());
            pageResult.setRecords(records);
            pageResult.setPageNum(devicePage.getCurrent());
            pageResult.setPageSize(devicePage.getSize());
            return pageResult;

    }

    @Override
    public Boolean cancelCommand(Command command) {
        // 构建客户端信息
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(ctwEntity.getAppKey())
                .appSecret(ctwEntity.getAppSecret())
                .build();

        CancelCommandRequest request = new CancelCommandRequest();
        request.addParamMasterKey(command.getMasterKey());

        // 构建请求体
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commandId", command.getCommandId());
        jsonObject.put("deviceId", command.getDeviceId());
        jsonObject.put("productId", command.getProductId());

        // 设置请求体为字节数组
        request.setBody(jsonObject.toString().getBytes());
        try {
            // 发送取消指令请求
            client.CancelCommand(request);
            // 打印请求体
            log.info("CancelCommand 请求体: {}", jsonObject.toString());
        } catch (Exception e) {
            // 处理异常
            log.error("取消指令时发生异常", e);
            return false;
        } finally {
            // 关闭客户端
            client.shutdown();
        }
        return true;
    }

    @Override
    public String getDtuId(String deviceAddress) {
        String dtuName = ctwingMapper.getDtuId(deviceAddress);
        return dtuName;
    }

    @Override
    public String getdeviceId(String deviceAddress) {
        return iimapper.getDeviceId(deviceAddress);
    }

    @Autowired
    private CtwEntity ctwEntity;
}
